//引入公共样式
require("../../assets/css/communal.less");

/* 引入工具js */
const dom = require("../../util/dom.js");

// 引入字体图标
require("../../assets/fonts/fitness-fonts/iconfont.css");

// 引入当前页样式
require("./register.less");

/* 引入验证码模块 */
const CaptchaMini = require("captcha-mini");

/* 引入axios模块 */
const axios = require("axios");

document.addEventListener("DOMContentLoaded", function () {
	/* 初始化captcha() */
	let captcha = new CaptchaMini();
	let codeInit = "";
	captcha.draw(dom.$("#captchal"), (r) => {
		codeInit = r.toLowerCase();
		console.log(codeInit);
	});

	/* 密码登录 */
	let pad = dom.$(".pad-log");
	pad.addEventListener("click", function () {
		location.href = "login.html";
	});

	// 点击眼睛看见密码
	let num = 0;
	dom.$("#closeEyes1").addEventListener("click", function () {
		num++;
		if (num % 2 === 1) {
			dom.$("#pwd1").type = "text";
			dom.$("#closeEyes1").className = "iconfont icon-yanjing";
		} else {
			dom.$("#pwd1").type = "password";
			dom.$("#closeEyes1").className = "iconfont icon-biyanjing";
		}
	});

	// 点击眼睛再次看见密码
	let number = 0;
	dom.$("#closeEyes2").addEventListener("click", function () {
		number++;
		if (number % 2 === 1) {
			dom.$("#pwd2").type = "text";
			dom.$("#closeEyes2").className = "iconfont icon-yanjing";
		} else {
			dom.$("#pwd2").type = "password";
			dom.$("#closeEyes2").className = "iconfont icon-biyanjing";
		}
	});

	/* 表单验证 */
	dom.$(".btn").addEventListener("click", function () {
		let errorNode = dom.$("#error");

		/* 手机号验证 */
		let tp = dom.$(".tp").value;
		let reg =
			/^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/;
		if (reg.test(tp)) {
			errorNode.textContent = "";
		} else {
			errorNode.textContent = "手机格式错误";
			return; /* 遇到错误停下来 */
		}

		/* 验证码验证 */
		let verify = dom.$(".verify").value.toLowerCase();
		console.log(dom.$(".verify"));
		if (verify === codeInit) {
			errorNode.textContent = "";
		} else {
			errorNode.textContent = "验证码输入错误";
			return;
		}

		/* 密码验证 */
		let psd = dom.$(".psd").value;
		let reg1 = /^[a-zA-Z]\w{5,17}$/;
		if (reg1.test(psd)) {
			errorNode.textContent = "";
		} else {
			errorNode.textContent = "请输入以字母开头的6-18位密码";
			return;
		}

		/* 确认密码验证 */
		let psd1 = dom.$(".psd1").value;
		if (psd === psd1) {
			errorNode.textContent = "";
		} else {
			errorNode.textContent = "输入密码不一致";
			return;
		}

		/* 通过验证发送请求 */
		axios
			.post("http://fitness.h5.itsource.cn:3701/api/user/register", {
				account: tp,
				password: psd,
			})
			.then((res) => {
				console.log(res);
				if (res.data.errno === 0) {
					location.href = "login.html";
					alert("注册成功啦");
				} else {
					alert("注册失败");
				}
			});
	});
});
